#include<stdio.h>
#include<time.h>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(){
	int fd;
	time_t ctime;
	struct tm * ctimestr;
	int linecount = 0;
	char buf[2];
	char buf2[32];
	fd = open("1.txt", O_RDWR | O_CREAT | O_APPEND, 0664);
	if(fd < 0){
		perror("fopen");
		return 0;
	}

	//每次读取一个字符
	while(read(fd, buf, 1) != 0){
		//如果读到的字符是\n,证明已有一行
		if('\n' == buf[0]){
			linecount++;
		}
	}

	while(1){
		ctime = time(NULL);
		ctimestr = localtime(&ctime);
		printf("%04d-%02d-%02d %02d:%02d:%02d\n", ctimestr->tm_year + 1900, ctimestr->tm_mon + 1, ctimestr->tm_mday, ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec);
		sprintf(buf2, "%d, %04d-%02d-%02d %02d:%02d:%02d\n", linecount, ctimestr->tm_year + 1900, ctimestr->tm_mon + 1, ctimestr->tm_mday, ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec);
		write(fd, buf2, strlen(buf2));
		linecount++;
		sleep(1);
	}

	close(fd);


}
